package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.anno.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    //新增菜品
    public void add(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //插入菜品基本信息
        dishMapper.add(dish);
        //插入口味数据
        List<DishFlavor> flavorsList = dishDTO.getFlavors();
        if(flavorsList != null && flavorsList.size() > 0){
            flavorsList.forEach(flavors->{
                flavors.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavorsList);
        }
    }

    //菜品分页查询
    public PageResult findByPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<Dish> dishList = dishMapper.findByPage(dishPageQueryDTO);
        Page<Dish> p=(Page<Dish>) dishList;
        return new PageResult(p.getTotal(),p.getResult());
    }

    //删除菜品
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        //判断是否存在起售中的菜品（若有至少一个，则抛异常）
        for(Long id : ids){
            Dish dish = dishMapper.findByStatusAndId(id);
            //存在起售中的菜品，不能删除
            if(dish != null && dish.getStatus() == 1){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断是否存在被套餐关联的菜品（若有至少一个，则抛异常）
        List<Long> setmealIds = setmealDishMapper.findSetmealIdsByDishIds(ids);
        //存在被套餐关联的菜品，不能删除
        if(setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品
        log.info("删除菜品：{}", ids);
        dishMapper.deleteByIds(ids);
        // 删除菜品口味信息
        log.info("删除菜品口味：{}", ids);
        dishFlavorMapper.deleteByDishIds(ids);
    }

    //根据id查询菜品
    public DishDTO findById(Long id) {
        DishDTO  dishDTO = dishMapper.findById(id);
        return dishDTO;
    }

    //修改菜品
    @Transactional(rollbackFor = Exception.class)
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        //先根据id删除菜品口味
        dishFlavorMapper.deleteByDishIds(Arrays.asList(dishDTO.getId()));
        //再插入菜品口味信息
        List<DishFlavor> flavorsList= dishDTO.getFlavors();
        if(flavorsList != null && flavorsList.size() > 0){
            flavorsList.forEach(flavors->{
                flavors.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavorsList);
        }
    }

    //    启用和禁用菜品
    public void status(Integer status, Long id) {
        Dish dish=new Dish();
        dish.setStatus(status);
        dish.setId(id);
        dishMapper.update(dish);
    }

    //根据分类id查询菜品
    public List<Dish> list(Long categoryId) {
        List<Dish> dishList = dishMapper.list(categoryId);
        return dishList;
    }

//    条件查询菜品和口味
    public List<DishVO> listWithFlavor(Long categoryId) {
        List<Dish> dishList = dishMapper.list(categoryId);
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
